package org.wddsicmd.app;
 
import org.wddsicmd.app.ButtonTabComponent;
import org.wddsicmd.dev.AndroidDeviceManager;
import org.wddsicmd.util.ResourceBundleUtil;
import org.wddsicmd.util.Log;
import org.wddsicmd.util.Resource;
import org.wddsicmd.widgets.CustomTabbedPaneUI;
import org.wddsicmd.widgets.ConnectionPanel;
import org.wddsicmd.widgets.MssPanel;
import org.wddsicmd.widgets.LCDPanel;
import org.wddsicmd.widgets.TouchPanel;
import org.wddsicmd.widgets.OthersPanel;

import java.lang.Object;

import java.io.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import java.awt.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.Timer;
import javax.swing.JTable;
import javax.swing.table.*;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.TreeModelListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.Document;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;

public class CodeEditorMain extends JFrame implements ActionListener, ConnectionPanel.DeviceChangeListener{

	private final static String TAG = "CodeEditorMain";

	private final static int ROOT_FRAME_DEFAULT_WIDHT = 1000;
	private final static int ROOT_FRAME_DEFAULT_HEIGHT = 600;

	private final static int TAB_PAGER_1 = 0;
	private final static int TAB_PAGER_2 = 1;
	private final static int TAB_PAGER_3 = 2;
	private final static int TAB_PAGER_4 = 3;
	private final static int TAB_PAGER_5 = 4;
	private final static int TAB_PAGER_6 = 5;
	private final static int TAB_PAGER_7 = 6;
	private final static int TAB_PAGER_8 = 7;
	private final static int TAB_PAGER_COUNT = 8;

	private int[] mDisabledTabs = new int[]{0, 0, 1, 1, 1, 0, 0, 0};
	private int mLastSelectedItem;

	protected ResourceBundleUtil mLabels;

      private ImageIcon mConnectionImageNormal;
      private ImageIcon mConnectionImageDisconnected;
	private Image mBackgroundImage;
	private ImageIcon mBackgroundImageIcon;

	private JPanel mContentPanel;

	private JTabbedPane mTabbedPane = new JTabbedPane();
	private CustomTabbedPaneUI mCustomTabbedPaneUI;
	private JPanel mTab1Panel;
	private JPanel mTab2Panel;
	private JPanel mTab3Panel;

	private JLabel mConnectionIcon;
	private JLabel mConnectionText;
	private ConnectionPanel mConnectionPanel;
	private MssPanel mMssPanel;
	private LCDPanel mLCDPanel;
	private TouchPanel mTouchPanel;
	private OthersPanel mOthersPanel;
	
	private static String mAppTitle;

/* doom-2015-11-2 11:58:4 
	private static IDevice device;
 doom-2015-11-2 11:58:4 */
	private AndroidDeviceManager mAndroidDeviceManager;
	private AndroidDeviceManager.StateChangeListener mStateChangeListener;
	private String mConnectedDevice;
	private int mConnectedDeviceCount = 0;
	
	public CodeEditorMain(String title) {
		super(title);
		
		initLabels();

/* doom-2015-11-2 14:46:15 
		mAndroidDeviceManager = new AndroidDeviceManager();
		mAndroidDeviceManager.initManager();
		mAndroidDeviceManager.createBridge();
 doom-2015-11-2 14:46:15 */
		mStateChangeListener = new AndroidDeviceManager.StateChangeListener(){
			@Override
			public void deviceConnected(IDevice dev) {
				Log.d(TAG, "Device connected: " + dev);
				if(mConnectionPanel != null && dev != null){
/* doom-2015-11-2 15:16:12 
					Log.d(TAG, "dev.getProperties():"+dev.getProperties());
 doom-2015-11-2 15:16:12 */
					mConnectionPanel.addDevice(dev.getSerialNumber());

					mConnectedDeviceCount++;
					if(mConnectedDeviceCount  > 0){
						mConnectionIcon.setIcon(mConnectionImageNormal);
					}
				}
			}
			@Override
			public void deviceDisconnected(IDevice dev) {
				Log.d(TAG, "Device disconnected: " + dev);
				if(mConnectionPanel != null && dev != null){
/* doom-2015-11-2 15:16:14 
					Log.d(TAG, "dev.getProperties():"+dev.getProperties());
 doom-2015-11-2 15:16:14 */
					mConnectionPanel.removeDevice(dev.getSerialNumber());

					mConnectedDeviceCount--;
					if(mConnectedDeviceCount <= 0){
						mConnectionIcon.setIcon(mConnectionImageDisconnected);
					}
				}
			}
		};
		Runnable runnable = new Runnable() {
			public void run() {
				mAndroidDeviceManager = new AndroidDeviceManager();
				mAndroidDeviceManager.initManager();
				mAndroidDeviceManager.createBridge();
				mAndroidDeviceManager.addStateChangeListener(mStateChangeListener);
			}
		};
		new Thread(runnable).start();
		
/* doom-2015-11-2 11:57:39 
		AndroidDebugBridge.init(false); 
 doom-2015-11-2 11:57:39 */
/* doom-2015-11-2 11:48:21 
		device = getDevice(0);
 doom-2015-11-2 11:48:21 */

/* doom-2015-11-2 11:57:37 
		Runnable runnable = new Runnable() {
			public void run() {
				while(true){
					if(device != null)
						Log.d(TAG, "runnable adb check isOnline:"+device.isOnline()+" device.isOffline():"+device.isOffline());
					else
						Log.d(TAG, "runnable adb check NULL");
					try{
						Thread.sleep(1000);		
					} catch (InterruptedException e) {
						Log.d(TAG, "runnable adb check InterruptedException");
					}					
				}
			}
		};
		new Thread(runnable).start();
 doom-2015-11-2 11:57:37 */
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				Font vFont = new Font("\u5b8b\u4f53", Font.PLAIN, 14);
				UIManager.put("ToolTip.font", vFont);
				UIManager.put("Table.font", vFont);
				UIManager.put("TableHeader.font", vFont);
				UIManager.put("TextField.font", vFont);
				UIManager.put("ComboBox.font", vFont);
				UIManager.put("TextField.font", vFont);
				UIManager.put("PasswordField.font", vFont);
				UIManager.put("TextArea.font", vFont);
				UIManager.put("TextPane.font", vFont);
				UIManager.put("EditorPane.font", vFont);
				UIManager.put("FormattedTextField.font", vFont);
				UIManager.put("Button.font", vFont);
				UIManager.put("CheckBox.font", vFont);
				UIManager.put("RadioButton.font", vFont);
				UIManager.put("ToggleButton.font", vFont);
				UIManager.put("ProgressBar.font", vFont);
				UIManager.put("DesktopIcon.font", vFont);
				UIManager.put("TitledBorder.font", vFont);
				UIManager.put("Label.font", vFont);
				UIManager.put("List.font", vFont);
				UIManager.put("TabbedPane.font", vFont);
				UIManager.put("MenuBar.font", vFont);
				UIManager.put("Menu.font", vFont);
				UIManager.put("MenuItem.font", vFont);
				UIManager.put("PopupMenu.font", vFont);
				UIManager.put("CheckBoxMenuItem.font", vFont);
				UIManager.put("RadioButtonMenuItem.font", vFont);
				UIManager.put("Spinner.font", vFont);
				UIManager.put("Tree.font", vFont);
				UIManager.put("ToolBar.font", vFont);
				UIManager.put("OptionPane.messageFont", vFont);
				UIManager.put("OptionPane.buttonFont", vFont);

				new CodeEditorMain(mAppTitle).initViews();
			}
		});
	}	

	@Override
	public void paint(Graphics g) {
		super.paint(g);
/* doom-2015-10-23 15:49:52 
		int widht = getWidth();
		int height = getHeight();
		Log.d("CodeEditorMain", "paint widht: "+ widht);
		Log.d("CodeEditorMain", "paint height: "+ height);	
 doom-2015-10-23 15:49:52 */
/* doom-2015-10-23 15:51:24 
		if(mBackgroundImage != null){
			g.drawImage(mBackgroundImage,0,0,getWidth(),getHeight(),this);
		}
 doom-2015-10-23 15:51:24 */
	}

	private void justinTest(){
		long Xmask = 212321323144L;
		long sum = Xmask;
		long total = 0L;
		long current = 0L;
		
		for(int index = 1; index < 13; index++){
			total = sum;
			sum = sum / 10;
			current = total - sum * 10;
			Log.d(TAG, "@justinTest current: " + current);
		}
		/*
		long firstValue = Xmask / (long)(Math.pow(10, 11));	
		Log.d(TAG, "@justinTest current: " + current);
		Xmask = Xmask - firstValue * (long)(Math.pow(10, 11));
		Log.d(TAG, "@justinTest Xmask: " + Xmask);
		*/
		for(int index = 0, count = 13; index < 12; index++, count--){
			long currentValue = Xmask / (long)(Math.pow(10, count-2));	
			Xmask = Xmask - currentValue * (long)(Math.pow(10, count-2));
			Log.d(TAG, "@justinTest currentValue:"+currentValue+" Xmask: " + Xmask);
		}
	}

	public void initViews() {

		//justinTest();
		
		mConnectionText = new JLabel(); 
		mConnectionText.setVerticalAlignment(JTextField.BOTTOM);
		mConnectionText.setHorizontalAlignment(JTextField.RIGHT);
		mConnectionIcon = new JLabel();
		mConnectionIcon.setVerticalAlignment(JTextField.BOTTOM);
		mConnectionIcon.setHorizontalAlignment(JTextField.RIGHT);
		mConnectionImageDisconnected = new ImageIcon();
		mConnectionImageNormal = new ImageIcon();
		Image image =Toolkit.getDefaultToolkit().createImage(getClass().getResource("/org/wddsicmd/res/images/disconnected.png"));
		mConnectionImageDisconnected.setImage(image);	
		image =Toolkit.getDefaultToolkit().createImage(getClass().getResource("/org/wddsicmd/res/images/connected.png"));
		mConnectionImageNormal.setImage(image);			
		mConnectionIcon.setIcon(mConnectionImageDisconnected);
		add(mConnectionIcon);
		add(mConnectionText);
		
		mTabbedPane.add(getStringFromLabels("tab_pane_item_1"), createPagerPanel(TAB_PAGER_1));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_2"), createPagerPanel(TAB_PAGER_2));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_3"), createPagerPanel(TAB_PAGER_3));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_4"), createPagerPanel(TAB_PAGER_4));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_5"), createPagerPanel(TAB_PAGER_5));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_6"), createPagerPanel(TAB_PAGER_6));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_7"), createPagerPanel(TAB_PAGER_7));
		mTabbedPane.add(getStringFromLabels("tab_pane_item_8"), createPagerPanel(TAB_PAGER_8));
/* doom-2015-10-22 18:41:25 
		mTabbedPane.setTabPlacement(JTabbedPane.RIGHT); 
 doom-2015-10-22 18:41:25 */
 		mCustomTabbedPaneUI = new CustomTabbedPaneUI(ROOT_FRAME_DEFAULT_WIDHT - 60, TAB_PAGER_COUNT);
		mCustomTabbedPaneUI.setDisabledTabs(mDisabledTabs);
		mTabbedPane.setUI(mCustomTabbedPaneUI); 
		mLastSelectedItem = TAB_PAGER_6;
		mTabbedPane.setSelectedIndex(mLastSelectedItem);
		mTabbedPane.addChangeListener(new ChangeListener(){
			@Override 
			public void stateChanged(ChangeEvent e){
/* doom-2015-10-23 15:42:14 
				Log.d("CodeEditorMain", "mTabbedPane stateChanged");
 doom-2015-10-23 15:42:14 */
 				int mSelectedIndex = mTabbedPane.getSelectedIndex();
				if(mDisabledTabs[mSelectedIndex] == 1){
	 				mTabbedPane.setSelectedIndex(mLastSelectedItem);
				}
				onComponentResized();
				mLastSelectedItem = mTabbedPane.getSelectedIndex();
			}
		});

		mBackgroundImageIcon = new ImageIcon();
		mBackgroundImage =Toolkit.getDefaultToolkit().createImage(getClass().getResource("/org/wddsicmd/res/images/window_background.png"));
		mBackgroundImageIcon.setImage(mBackgroundImage);		

		setLayout(null);
		getContentPane().setBackground(Resource.getBackgroundColor());
		add(mTabbedPane);

/* doom-2015-10-23 17:47:32 
		JLabel bgPanel = new JLabel(mBackgroundImageIcon);
		bgPanel.setBounds(0, 0, mBackgroundImageIcon.getIconWidth(),
		mBackgroundImageIcon.getIconHeight());
		JPanel contentPanel = (JPanel) this.getContentPane();
		contentPanel.setOpaque(false);
		contentPanel.setLayout(null);		
		contentPanel.add(mTabbedPane);
		
		this.getLayeredPane().setLayout(null);
		this.getLayeredPane().add(bgPanel, new Integer(Integer.MIN_VALUE));
 doom-2015-10-23 17:47:32 */

		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				onComponentResized();
			}
		});			
		
		setSize(new Dimension(ROOT_FRAME_DEFAULT_WIDHT,ROOT_FRAME_DEFAULT_HEIGHT));		
		onComponentResized();
		setLocationRelativeTo(null);
		setVisible(true);	
	}	

	protected void initLabels() {
		mLabels = ResourceBundleUtil.getLAFBundle("org.wddsicmd.res.Labels");

		mAppTitle = getStringFromLabels("app_title");
	}	
	public String getStringFromLabels(String key){
		return Resource.getStringFromLabels(mLabels, key);
	}

	public void onComponentResized(){
		int width = getWidth();
		int height = getHeight();

/* doom-2015-11-2 11:12:21 
		Log.d("CodeEditorMain", "onComponentResized width: "+ width);
		Log.d("CodeEditorMain", "onComponentResized height: "+ height);
 doom-2015-11-2 11:12:21 */

		int cellWidth = (width - 60) / TAB_PAGER_COUNT;
		int iconWidth = 30;
		int textWidth = cellWidth * 3;
/* doom-2015-11-2 16:22:0 
		mConnectionIcon.setBounds(new Rectangle(30 + (cellWidth-iconWidth)/2, 0 , 30, 30));
 doom-2015-11-2 16:22:0 */ 		
		mConnectionText.setBounds(new Rectangle(width - 60 - textWidth, height - 80 , textWidth, iconWidth));
		mConnectionIcon.setBounds(new Rectangle(width - 60, height - 80 , iconWidth, iconWidth));

		mTabbedPane.setBounds(new Rectangle(30, 30 , width - 60, height - 60));

		mCustomTabbedPaneUI.updateTabAreaInsets(width - 60);

		int mSelectedIndex = mTabbedPane.getSelectedIndex();
/* doom-2015-10-29 18:26:53 
		Log.d("CodeEditorMain", "onComponentResized mSelectedIndex: "+ mSelectedIndex);		
 doom-2015-10-29 18:26:53 */
/* doom-2015-11-2 16:21:20 
		if(mSelectedIndex == TAB_PAGER_6){
			mLCDPanel.repaint();
		}
 doom-2015-11-2 16:21:20 */
	}
	public void actionPerformed(ActionEvent e) {
		
	}	

	private Component createPagerPanel(int index) {

		switch(index){
			case TAB_PAGER_6:
			mLCDPanel = new LCDPanel(this, getStringFromLabels("tab_pane_item_6"));
			return mLCDPanel;

			case TAB_PAGER_7:
			mTouchPanel = new TouchPanel(this, getStringFromLabels("tab_pane_item_7"));
			return mTouchPanel;

			case TAB_PAGER_8:
			mOthersPanel = new OthersPanel(this, getStringFromLabels("tab_pane_item_8"));
			return mOthersPanel;

			
			case TAB_PAGER_1:
			mConnectionPanel = new ConnectionPanel(this, getStringFromLabels("tab_pane_item_1"));
			mConnectionPanel.addDeviceChangeListener(this);
			return mConnectionPanel;

			case TAB_PAGER_2:
			mMssPanel = new MssPanel(this, getStringFromLabels("tab_pane_item_2"));
			return mMssPanel;

			case TAB_PAGER_3:
			mOthersPanel = new OthersPanel(this, getStringFromLabels("tab_pane_item_3"));
			return mOthersPanel;
			
		}	

		return null;
	}	
/* doom-2015-11-2 11:58:14 

	private static IDevice getDevice(int index) {
		IDevice device = null;
		AndroidDebugBridge bridge = AndroidDebugBridge.createBridge("adb", true);        
		waitDevicesList(bridge);
		IDevice devices[] = bridge.getDevices();
		if(devices.length < index || devices == null){
			System.err.print("\u6ca1\u6709\u68c0\u6d4b\u5230\u7b2c" + index + "\u4e2a\u8bbe\u5907");
		}else{
			for(IDevice onlinedevice : devices){
				Log.d(TAG, "getDevice onlinedevice.getSerialNumber():"+onlinedevice.getSerialNumber());
			}
			device = devices[index];
		}
		return device;
	}
	private static void waitDevicesList(AndroidDebugBridge bridge) {
		int count = 0;
		while (bridge.hasInitialDeviceList() == false) {
			try {
				Thread.sleep(500);
				count++;
			} catch (InterruptedException e) {
			}
			if (count > 10) {
				System.err.print("\u7b49\u5f85\u83b7\u53d6\u8bbe\u5907\u8d85\u65f6");
				break;
			}
		}
	}
 doom-2015-11-2 11:58:14 */

	public void deviceChanged(String serialNumber){
		mConnectedDevice = serialNumber;
		Log.d(TAG, "deviceChanged mConnectedDevice:"+mConnectedDevice);
		if(mConnectedDevice != null){
			mConnectionText.setText("[Current Device name: "+mConnectedDevice+"]");
		}else{
			mConnectionText.setText("[No device connected.]");
		}
	}

	public String getConnectedDevice(){
		return mConnectedDevice;
	}

}



	  
